package com.helu.lubike.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.helu.lubike.R;
import com.helu.lubike.api.INetService;
import com.helu.lubike.model.BTParam;
import com.helu.lubike.utils.Constants;
import com.helu.lubike.utils.HTTPHelper;
import com.helu.lubike.utils.SharedPreferencesUtils;
import com.helu.lubike.utils.Utils;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @author helu  17-2-7 上午11:35
 * @description 启动页
 */

public class LauncherActivity extends AppCompatActivity {

    private static final String MSG = "LauncherActivity";

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
            return false;
        }
    });
    private Subscription subscribe;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);

        initData();
    }

    private void initData() {
        subscribe = HTTPHelper.getInstance().create(INetService.class)
                .getBTParam()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BTParam>() {
                    @Override
                    public void call(BTParam btParam) {
                        if (btParam.code == 200) {
                            SharedPreferencesUtils.save(LauncherActivity.this, Constants.BTA, btParam.data.bta);
                            SharedPreferencesUtils.save(LauncherActivity.this, Constants.BTN, btParam.data.btn);
                        } else {
                            Utils.showToast(LauncherActivity.this, btParam.message);
                        }
                        jump();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.d(MSG, "请求失败," + throwable.getMessage());
                        jump();
                    }
                });
    }

    private void jump() {
        Message msg = new Message();
        mHandler.sendMessageDelayed(msg, 2000);
    }

    @Override
    protected void onDestroy() {
        if (subscribe != null) {
            subscribe.unsubscribe();
        }

        super.onDestroy();
    }
}
